package com.livi.tools.cas_general_backend.controller.cas;

import com.livi.tools.cas_general_backend.entity.response.Res;
import com.livi.tools.cas_general_backend.entity.response.ResData;
import com.livi.tools.cas_general_backend.entity.response.ResStatusEnum;
import com.livi.tools.cas_general_backend.entity.sys.LoginUser;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping(value = "/auth")
public class AuthController {
    @Value("${myapp.cas-login-url}")
    private String loginUrl;
    @Value("${myapp.cas-logout-url}")
    private String logoutUrl;

    @RequestMapping(value = "cas", method = RequestMethod.GET)
    public void cas(HttpServletResponse response, String currentPath) throws IOException {
        response.sendRedirect(loginUrl + currentPath);
    }

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public void login(HttpServletRequest request, HttpServletResponse response, String currentPath) throws IOException {
        AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
        String username = principal.getName();
        HttpSession session = request.getSession();
        session.setAttribute("loginUser", new LoginUser()
                .setToken(username)
                .setAccount(username)
                .setName("admin")
                .setRoles(new String[]{"admin"})
                .setPermissions(new String[]{"lis.setting", "lis.pon"}));
        response.sendRedirect(currentPath);
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public Res logout(HttpServletRequest request, HttpServletResponse response, String currentPath)
            throws IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        return Res.success(ResStatusEnum.logout);
        //response.sendRedirect(logoutUrl);
    }

    @RequestMapping(value = "user", method = RequestMethod.GET)
    public Res user(HttpServletRequest request) {
        HttpSession session = request.getSession();
        LoginUser loginUser = (LoginUser) session.getAttribute("loginUser");
        return ResData.success(loginUser);
    }

}
